<script setup>
import {Avatar, Message} from "@element-plus/icons-vue";
import {ref, watch} from "vue";
import {saveComment} from "@/api/comment.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import validateUtil from "@/utils/validateUtil.js";

const $router = useRouter();

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: true
  },
  parentId: {
    type: Number,
    default: 0
  }
});

const emits = defineEmits(['update:modelValue', 'refresh']);

const isShowReply = ref(props.modelValue);

watch(() => props.modelValue, (newValue) => {
  // console.log('submit-->',newValue)
  isShowReply.value = newValue;
  emits('update:modelValue', newValue);
}, {deep: true});

const commentForm = ref({
  nickname: '',
  email: '',
  content: '',
});

const loading = ref(false);

const submit = async () => {
  console.log(commentForm.value);
  const {id} = $router.currentRoute.value.params;
  // console.log('文章ID=', id)
  if (!id) {
    ElMessage.warning('文章ID不存在');
    return;
  }
  let validation = validateUtil.required(commentForm.value.nickname, '请填写昵称')
      || validateUtil.required(commentForm.value.email, '请填写邮箱')
      || validateUtil.email(commentForm.value.email)
      || validateUtil.required(commentForm.value.content, '请填写评论内容');
  if (validation) {
    ElMessage.warning(validation);
    return;
  }
  const request = {
    postId: id,
    ...commentForm.value,
    parentId: props.parentId
  };
  loading.value = true;
  // 调用评论新增接口
  await saveComment(request).then(res => {
    console.log('--->', res);
    ElMessage.success('评论成功');
    loading.value = false;
    emits('refresh');
  }).catch(err => {
    console.log(err);
    loading.value = false;
  });
};
</script>

<template>
  <div v-if="isShowReply" class="v-reply-form">
    <el-input v-model="commentForm.content" :rows="3" :autosize="{ minRows: 3, maxRows: 3 }" type="textarea"
              show-word-limit maxlength="255" placeholder="请输入评论内容"/>
    <div>
      <el-input v-model="commentForm.nickname" placeholder="请输入昵称" clearable :prefix-icon="Avatar"/>
      <el-input v-model="commentForm.email" placeholder="请输入邮箱" clearable :prefix-icon="Message"/>
      <el-button type="success" @click="submit" :loading="loading">提交评论</el-button>
    </div>
  </div>
</template>

<style scoped>
/* 重写 element plus 样式 */
:deep(.el-textarea__inner) {
  resize: none;
}

.v-reply-form {
  padding: 4px 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  
  > div {
    padding: 4px 0;
    display: flex;
    justify-content: space-between;
    gap: 30px;
  }
}
</style>